package com.ruoyi.common.utils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.NumberSerializer;
import com.fasterxml.jackson.databind.ser.std.NumberSerializers;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Json工具类，各种Json序列化反序列化方式<br>
 * 底层使用Jackson实现，支持Jackson的各种注解
 *
 */
public final class JacksonUtils {
    private static final Logger logger = LoggerFactory.getLogger(JacksonUtils.class);

    private JacksonUtils() {
    }

    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")); // 时间戳处理
        MAPPER.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 时区
//        MAPPER.setSerializationInclusion(Include.NON_NULL); // 序列化忽略null
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); // 反序列化忽略未知字段
        MAPPER.writer().with(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS); // 特殊字符处理
        MAPPER.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE); // 忽略set方法
        MAPPER.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE); // 忽略get方法
        MAPPER.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); // 使用FIELD
        final JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern("HH:mm:ss")));
        MAPPER.registerModule(javaTimeModule);
        final SimpleModule bigDecimalModule = new SimpleModule();
        bigDecimalModule.addSerializer(NumberSerializer.bigDecimalAsStringSerializer());
        MAPPER.registerModule(bigDecimalModule);
        MAPPER.findAndRegisterModules();
    }

    public static ObjectMapper getObjectMapper() {
        return MAPPER;
    }

    /**
     * 对象转换成Json字符串
     *
     * @param obj 要转换的对象
     * @return
     */
    public static String writeValueAsString(Object obj) {
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (Exception e) {
            logger.error("JacksonUtils序列化失败，原对象：[{}]", obj);
            throw new RuntimeException("JacksonUtils-Json序列化失败，失败原因：" + e.getMessage(), e);
        }
    }

    /**
     * 将json字符串反序列化成对象
     *
     * @param <T>
     */
    public static <T> T readValue(String str, Class<T> clazz) {
        try {
            return MAPPER.readValue(str, clazz);
        } catch (Exception e) {
            logger.error("JacksonUtils序列化失败，json字符串[{}]，目标类型：[{}]", str, clazz.getSimpleName());
            throw new RuntimeException("Json反列化失败，失败原因：" + e.getMessage(), e);
        }
    }

    /**
     * 将json字符串反序列化成对象
     *
     * @param <T>
     */
    public static <T> T readValue(String str, TypeReference<T> typeReference) {
        try {
            return MAPPER.readValue(str, typeReference);
        } catch (Exception e) {
            throw new RuntimeException("Json反列化失败，失败原因：" + e.getMessage(), e);
        }
    }

    /**
     * 将对象视为Json形式转换成对象
     *
     * @param <T>
     * @return
     */
    public static <T> T convert(Object val, Class<T> clazz) {
        return readValue(writeValueAsString(val), clazz);
    }

    /**
     * 将对象视为Json形式转换成对象
     *
     * @param <T>
     * @return
     */
    public static <T> T convert(Object val, TypeReference<T> typeReference) {
        return readValue(writeValueAsString(val), typeReference);
    }
}
